<template>
  <el-row>
    <el-col class="full-height" :span="24">
      <el-container class="bg-white">
        <el-aside class="bg-aside" width="340px">
          <el-row>
            <!--菜单-->
            <el-col class="full-height col-auto">
              <el-menu default-active="1" class="full-height el-menu-vertical-demo" :collapse="uiData.isCollapse">
                <el-menu-item @click="uiMethods.changePage" index="1">
                  <el-icon>
                    <UserFilled />
                  </el-icon>
                  <template #title>联系人</template>
                </el-menu-item>
                <el-menu-item @click="uiMethods.changePage" index="2">
                  <el-icon>
                    <Message />
                  </el-icon>
                  <template #title>通知</template>
                </el-menu-item>
              </el-menu>
            </el-col>
            <!--消息列表、好友列表等-->
            <el-col :span="19" class="p-2">
              <!--用户欢迎词-->
              <el-row id="userRef" ref="userRef" class="w-100">
                <el-col :span="6">
                  <el-avatar :src="uiData.defaultAvatar" :size="50" />
                </el-col>
                <el-col :span="12">
                  <div>{{ uiData.name }}</div>
                </el-col>
                <el-col :span="3"> </el-col>
              </el-row>
              <!--搜索栏-->
              <el-row class="mt-2" id="searchRef" ref="searchRef">
                <el-col :span="22">
                  <el-input :disabled="uiData.disableSearchButton" v-model="uiData.searchKeyWord"
                    @change="uiMethods.searchMyFriend" placeholder="输入姓名/账号搜索好友" :prefix-icon="Search" />
                </el-col>
                <el-col :span="2">
                  <el-dropdown trigger="click">
                    <span class="el-dropdown-link mt-1 ms-2">
                      <el-icon :size="20">
                        <Plus />
                      </el-icon>
                    </span>

                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item :icon="Plus" @click="uiMethods.openSearchDialog(1)">
                          添加好友
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col>
              </el-row>
              <!--好友列表、群组列表等各种列表-->
              <el-row :style="{ height: uiData.chatRoomHeight + 'px' }" class="mt-4" id="chatRoomRef" ref="chatRoomRef">
                <el-col :span="24">
                  <el-scrollbar key="ui-scrollbar" :height="uiData.chatRoomHeight">
                    <Friends @open-window="uiMethods.openWindow" @apply-chat-status="uiMethods.setApplyChatStatus"
                      :height="uiData.chatRoomHeight" v-if="uiData.menu === '1'" :list="uiData.contactList" />
                    <Notice v-if="uiData.menu === '2'" :height="uiData.chatRoomHeight" />
                  </el-scrollbar>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-aside>
        <!--聊天窗口-->
        <el-row class="w-100">
          <BlankPage v-if="uiData.openChatRoom === false" />
          <ChatWindow :friend-info="uiData.privateFriendInfo" :apply-chat-status="uiData.applyChatStatus"
            v-if="uiData.openChatRoom === true" />
        </el-row>
      </el-container>
    </el-col>
  </el-row>
  <el-dialog v-model="uiData.dialogTableVisible" :title="uiData.dialogIndex === 1
      ? '添加好友'
      : uiData.dialogIndex === 2
        ? '加入群组'
        : '创建群组'
      " width="480">
    <AddFriends v-if="uiData.dialogIndex === 1" />
  </el-dialog>
</template>

<script lang="ts" setup>
import Friends from '@renderer/components/friends.vue';
// import ChatMessage from '@renderer/components/chatMessage.vue';
import AddFriends from '@renderer/components/addFriends.vue';
// import Group from '@renderer/components/group.vue';
import Notice from '@renderer/components/notice.vue';
import ChatWindow from '@renderer/components/chatWindow.vue';
import BlankPage from '@renderer/components/blankPage.vue';
import {
  Search,
  UserFilled,
  // ChatDotSquare,
  Message,
  Plus
} from '@element-plus/icons-vue';
// 引入所需对应的Vue API
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { format } from 'timeago.js';
import { ElMessage } from 'element-plus';
import { useStore } from '../common/piniaStore';
import { Message_File } from '@renderer/common/type';
import { defaultAvatar } from '../common/resource';

const uiData = ref({
  menu: '1',
  isCollapse: true,
  chatRoomHeight: 0,
  dialogTableVisible: false,
  dialogIndex: 1,
  contactList: new Array() as Array<{
    friendId: string;
    friendUserName: string;
    friendName: string;
    createTime: string;
    online?: boolean;
  }>,
  name: '测试1',
  openChatRoom: false,
  userId: '1234567890123',
  privateFriendInfo: {} as {
    friendId: string;
    friendUserName: string;
    friendName: string;
    createTime: string;
  },
  applyChatStatus: false,
  messageList: [] as Array<
    {
      senderId: string;
      receiverId: string;
      timestamp: number;
      message: string,
      senderName: string
    }
  >,
  defaultAvatar: defaultAvatar,
  searchKeyWord: null,
  disableSearchButton: false
});

const store = useStore();

const msg = ElMessage({
  type: 'warning',
  message: '等待初始化...',
  duration: 0,
  showClose: true
});

const staticUiData = {
  init: false
}

window.electron.ipcRenderer.on('user-info', (_, data) => {
  uiData.value.name = data.name;
  uiData.value.userId = data.userId;
});

window.electron.ipcRenderer.on('ipc:refresh-friend-list', (_event, _data) => {
  uiMethods.getContactList();
})

//等待Socket客户端初始化完成
window.electron.ipcRenderer.once('ipc:socket-init-success', async () => {
  uiData.value.contactList = [];
  //获取好友列表，如果文件跟好友列表对不上，则创建对应的好友私聊消息记录文件
  const result = await axios.get('/getContactList', {
    params: { page: 1, size: 100 }
  });

  const list: Array<{
    friendId: string;
    friendUserName: string;
    friendName: string;
    createTime: string;
  }> = result.data.data;

  store.client?.connectionSocket(list.map(item => { return item.friendId }));

  const temp = new Array(...list).map(item => {
    return {
      friendId: item.friendId,
      friendUserName: item.friendUserName,
      friendName: item.friendName,
      createTime: format(item.createTime, 'zh_CN')
    }
  });

  window.electron.ipcRenderer.send(
    'init-chat-message-files',
    uiData.value.userId,
    temp.map(item => {
      return {
        friendId: item.friendId,
        friendName: item.friendName
      }
    }));


});

window.electron.ipcRenderer.on('key-init-status', (_event, status) => {
  console.log('程序启动状态：', status);
  if (status) {
    staticUiData.init = true;
    store.appInit = true;
    msg.close();
    ElMessage({
      type: 'success',
      message: '密钥初始化完成',
      duration: 2000,
      showClose: true
    });
  }
});

window.electron.ipcRenderer.on('init-chat-message-files', (_event, data: Array<Message_File>) => {
  store.localMessages = data;
});

window.electron.ipcRenderer.once(
  'get-private-chat-message',
  (_event, jsonMsg: any[]) => {
    uiData.value.messageList = jsonMsg;
  }
);

// 控制好友在线的头像状态
window.electron.ipcRenderer.on('ipc:friend-online', (_, friendId: string, status: boolean) => {
  console.log('有好友状态改变！ ', friendId, status);
  for (let friend of uiData.value.contactList) {
    if (friend.friendId === friendId) {
      //发送系统消息
      window.electron.ipcRenderer.send(
        'show-system-message',
        '状态消息',
        `好友"${friend.friendName}"${status ? '已登录' : '已下线'}`
      );
      friend.online = status;
      break;
    }
  }
});

window.electron.ipcRenderer.on('ipc:remove-key-negotiation-user', () => {
  uiMethods.setApplyChatStatus(false);
});

window.electron.ipcRenderer.on('ipc:close-chat-window', () => {
  uiData.value.openChatRoom = false;
});

window.electron.ipcRenderer.on('ipc:change-submit-message-button',
  (_, senderId: string, _friendId: string, status: boolean) => {
    if (uiData.value.privateFriendInfo.friendId === senderId) {
      uiData.value.applyChatStatus = status;
    }
  });

onMounted(async () => {
  //获取本地私聊消息
  window.electron.ipcRenderer.send('get-private-chat-message');
  uiMethods.setDefaultHeight();
});

const uiMethods = {
  /**
   * 设置默认高度
   */
  setDefaultHeight: () => {
    let userElement = document.getElementById('userRef');
    let searchElement = document.getElementById('searchRef');
    let chatRoomElement = document.getElementById('chatRoomRef');

    if (userElement && searchElement && chatRoomElement) {
      let totalHeight = document.documentElement.clientHeight;
      let userHeight = userElement.offsetHeight;
      let searchHeight = searchElement.offsetHeight;

      // 计算 chat-room 的高度
      let chatRoomHeight = totalHeight - userHeight - searchHeight - 65;
      uiData.value.chatRoomHeight = chatRoomHeight;
    }
  },
  /**
   * 打开功能菜单窗口
   * @param index 1：添加好友 2：加入群组 3：创建群组
   */
  openSearchDialog: (index: number) => {
    uiData.value.dialogIndex = index;
    uiData.value.dialogTableVisible = true;
  },
  /**
   * 切换功能菜单
   * @param index
   */
  changePage: (event: any) => {
    if (event.index === '1') {
      uiMethods.getContactList();
      uiData.value.disableSearchButton = false;
    }
    if (event.index === '2') {
      uiData.value.disableSearchButton = true;
    }
    uiData.value.menu = event.index;
  },
  /**
   * 获取好友列表
   */
  getContactList: async (keyWord?: string) => {
    uiData.value.contactList = [];

    console.log('已点击');
    const result = await axios.get('/getContactList', {
      params: keyWord ? { page: 1, size: 100, keyWord: keyWord } : { page: 1, size: 100 }
    });

    const list: Array<{
      friendId: string;
      friendUserName: string;
      friendName: string;
      createTime: string;
    }> = result.data.data;
    console.log('返回的好友列表：', list);

    store.client!.getFriendsOnline(list.map(item => item.friendId));

    window.electron.ipcRenderer.once(
      'ipc:client-online-status',
      (
        _,
        clientsOnline: Array<{ id: string; isLine: boolean }>
      ) => {
        for (const item of list) {
          const online = clientsOnline.find(res => res.id === item.friendId);
          uiData.value.contactList.push({
            friendId: item.friendId,
            friendUserName: item.friendUserName,
            friendName: item.friendName,
            createTime: format(item.createTime, 'zh_CN'),
            online: online ? online.isLine : false
          });
        }
      });

  },
  openWindow(
    userInfo: {
      friendId: string;
      friendUserName: string;
      friendName: string;
      createTime: string;
    }
  ) {

    uiData.value.openChatRoom = false;
    uiData.value.openChatRoom = true;
    uiData.value.privateFriendInfo = userInfo;
    window.electron.ipcRenderer.send('ipc:update-chat-window');
  },
  setApplyChatStatus(status: boolean) {
    console.log('设置的状态：', status);
    uiData.value.applyChatStatus = status;
  },
  /**
   * 搜索自己的好友
   * @param keyWord 关键词
   */
  async searchMyFriend(keyWord: string): Promise<void> {
    //当菜单是好友列表时，搜索好友
    uiMethods.getContactList(keyWord);
  }
};



</script>

<style lang="scss" scoped>
.full-height {
  height: 100vh;
  /* 设置容器高度为视口高度 */
}

.bg-aside {
  background-color: #f5f5f5;
}

.h-10 {
  height: 10vh;
}
</style>
